﻿@{
    ViewBag.Title = "Index";
}
<div id="gameArea">

    <div id="toolbar">
        <button id="start">Start Game!</button>
    </div>
    <div id="gameBoard" style="display: inline-block">
    </div>
    <div id="players" style="display: inline-block; vertical-align: top">
        <h2>Players</h2>
        <ul id="playerList">
        </ul>
    </div>
</div>
<script type="text/javascript">
    var ws = null;
    var wsPickFirst = null;
    var gameViewModel = { players: new Array() };

    gameViewModel.addPlayer = function (player) {
        gameViewModel.players.push(player);
    };

    gameViewModel.removePlayer = function (player) {
        var indexOfPlayer = gameViewModel.indexOfPlayer(player.PlayerId);
        if (indexOfPlayer != -1)
            gameViewModel.players.splice(indexOfPlayer, 1);
    };
    gameViewModel.indexOfPlayer = function (id) {
        for (var i = 0; i < gameViewModel.players.length; i++) {
            var player = gameViewModel.players[i];
            if (player.PlayerId == id)
                return i;
        }
        return -1;
    };
    gameViewModel.synchPlayers = function (players) {
        for (var i = 0; i < players.length; i++) {
            gameViewModel.addPlayer(players[i]);
        }
    };

    gameViewModel.synchScores = function (scores) {
        for (var i = 0; i < scores.length; i++) {
            var scoreItem = scores[i];

            var playerindex = gameViewModel.indexOfPlayer(scoreItem.PlayerId);
            if (playerindex == -1) {
                return;
            }
            var player = gameViewModel.players[playerindex];
            player.Score = scoreItem.Score;
        }
    };

    $(function () {
        var wsUri = "ws://127.0.0.1:4502/GenericText";
        var wsPickFirstUri = "ws://127.0.0.1:4502/PickFirstHandler";

        ws = new jXSockets.xWebSocket(wsUri);
        wsPickFirst = new jXSockets.xWebSocket(wsPickFirstUri);

        wsPickFirst.bind("OnShapeHit", function (shape) {
            $("#" + shape.Id).fadeOut(100);

        });

        ws.bind("OnNewShape", function (msg) {
            makeDiv(msg.Guid, msg.PosX, msg.PosY, msg.Divsize, msg.Color);
        });

        wsPickFirst.bind("OnGameStarted", function (msg) {
            $("#start").attr('disabled', true);
            // gameViewModel.synchPlayers(msg);
        });

        $(".shape").live("click", function () {
            var id = $(this).attr("id");
            wsPickFirst.trigger("OnShapeHit", { Id: id }, function () { createNewShape(); });

        });

        bindSocketEvents(ws);
        bindSocketEvents(wsPickFirst);

        $("#start").click(function () {
            wsPickFirst.trigger("OnGameStarted", {});
            createNewShape();
        });

        wsPickFirst.bind("OnPlayerConnected", function (data) {
            if (gameViewModel.players.length == 0) {
                gameViewModel.synchPlayers(data.All);
                $("#start").attr('disabled', true);
            }
            else {
                gameViewModel.addPlayer(data.Connected);
                $("#start").attr('disabled', false);
            }
            synchPlayerList();
        });

        wsPickFirst.bind("OnPlayerDisconnected", function (data) {
            gameViewModel.removePlayer(data.Disconnected);
            synchPlayerList();
        });

        wsPickFirst.bind("OnScoreChanged", function (data) {
            gameViewModel.synchScores(data);
            synchPlayerList();
        });

        wsPickFirst.bind("OnGameEnded", function (data) {
            $.colorbox({ html: '<div id="gameMessage"><p>Game has ended</p><p>Winner is: ' + data.PlayerId + '</p></div>', width: 400, height: 150 });
            $(".shape").remove();
        });

    });

    function createNewShape() {
        var guid = makeGuid();

        var divsize = ((Math.random() * 100) + 50).toFixed();
//        var color = Math.round(0xffffff * Math.random()).toString(16);
//        color = color > 0xe6e6e6 && color <= 0xffffff ? 0x000000 : color;
        var posx = (Math.random() * ($('#gameBoard').width() - divsize)).toFixed();
        var posy = (Math.random() * ($('#gameBoard').height() - divsize)).toFixed();
        console.log(ws);
        ws.trigger("OnNewShape", { Guid: guid, Divsize: divsize, Color: "#000000", PosX: posx, PosY: posy });
    }

    function makeDiv(guid, posx, posy, divsize, color) {

        $newdiv = $('<div class="shape" id=' + guid + '/>').css({
            'width': divsize + 'px',
            'height': divsize + 'px',
            'z-index': '1000',
            'background-color': color
        });

        $newdiv.css({
            'position': 'absolute',
            'left': posx + 'px',
            'top': posy + 'px',
            'display': 'none'
        }).appendTo('#gameBoard').fadeIn(100);
    }

    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    function makeGuid() {
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }



    function synchPlayerList() {
        $("#playerList").children().remove();
        for (var i = 0; i < gameViewModel.players.length; i++) {
            var player = gameViewModel.players[i];
            $("#playerList").append("<li>" + player.PlayerId + " Score: " + player.Score + "</li>");
        }
    }

    function bindSocketEvents(wsSocket) {
        wsSocket.bind("close", function (msg) {
            console.log("Closed " + msg);
        });

        wsSocket.bind("FailConnect", function (msg) {
            console.log("Failed " + msg);
        });

        wsSocket.bind("open", function (msg) {
            console.log("Open " + msg);
        });
    }



</script>
